﻿using EasyNetQ;
using EasyNetQTest.AspnetCore.Config;
using EasyNetQTest.AspnetCore.Models;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace EasyNetQTest.AspnetCore.Services
{
    /// <summary>
    /// 后台运行的任务
    /// 消息消费者，1个消费者
    /// </summary>
    public class MQRecieveService : BackgroundService
    {
        public MQRecieveService(IBus bus)
        {
            this.bus = bus;
        }

        //MQ消息总线
        IBus bus;

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //直接从队列中接收消息
            bus.Receive<MQMessage>(Consts.QueueName, o =>
            {
                Console.WriteLine("收到消息: {0}", o.MsgContent);

                Thread.Sleep(50);//模拟耗时,进行消息处理                        
                Console.WriteLine("消息处理结束\n");
            });

            return Task.CompletedTask;
        }
    }
}
